const https = require('https');
//雪花算法生成id
const snowflake = require('./Snowflake')
let SQLHelp = require('./SQLHelp')
const {formatTime} = require('./util')
const multer = require('multer')
const storage = multer.diskStorage({
    destination:'./uploads',
    filename: function(req,file,cb){
        let fileType = file.originalname.split('.')
        fileType = fileType[fileType.length - 1]
        cb(null,snowflake() + '.' + fileType)
    },
    
})
const upload = multer({storage:storage})
module.exports = function(app){
    //登录拦截中间件
    function loginRouter(req,res,next){
        if(req.method == 'OPTIONS'){
            next()
            return;
        }
        let token = req.headers.token
        if(token){
            SQLHelp(`select * from session where id = ${token} and state = 1`).then(ret => {
                if(ret.length){
                    let session = ret[0]
                    //2H
                    if(new Date().getTime() - session.createTime < 2 * 60 * 60 * 1000){
                        req.session = {
                            userId:session.userId,
                            userName:session.userName
                        }
                        next()
                    }else{
                        res.status(400).send({errorMsg:'登录超时'})
                    }
                }else{
                    res.status(400).send({errorMsg:'当前用户未登录'})
                }
            })
        }else{
            res.status(400).send({errorMsg:'缺少token,请先进行登录'})
        }
        
    }
    //让初登陆以为的所有小程序接口都先验证登录
    app.use('/admin',loginRouter)
    //文件上传
    app.post('/upload',upload.single('file'),(req,res) => {
        console.log(req.file)
       res.send(req.file) 
    })

    //管理后台登录
    app.post('/login',(req,res) => {
        let userName = req.body.userName
        let passWord = req.body.passWord
        if(userName && passWord){
            SQLHelp(`
                select * from user where userName = '${userName}'
            `).then(users =>{
                if(users.length){//正常登录
                    let user = users[0]
                    if(passWord == user.passWord){
                        let token = snowflake()
                        //缓存token到session表
                        SQLHelp(`
                        insert into session(id,userId,userName,inTime,createTime,platform)
                        values ('${token}','${user._id}','${user.nickName}','${formatTime(new Date())}','${new Date().getTime()}','admin')
                        `).then(ret => {
                            res.send({
                            nickName:user.nickName,
                            token,
                            avatarUrl:user.photo,
                            _id:user._id
                        })
                        })
        
                    }else{
                        res.send({errorMsg:'密码错误'})
                    }
                }else{
                    res.send({errorMsg:'用户名不存在'})
                }
            })
        }else{
            res.send({errorMsg:'用户名和密码不能为空'})
        }
    })
   //退出登录
   app.get('/admin/logout',(req,res) => {
       SQLHelp(`
       UPDATE session SET outTime = '${formatTime(new Date())}',state = 0
       WHERE id = '${req.headers.token}'
       `).then(ret => {
           res.send({msg:'退出登录成功'})
       })
   })
   //修改密码
   app.post('/admin/changePassword',(req,res) => {
       let userId = req.session.userId
       let passWord = req.body.password
       let newPassWord = req.body.newpassword
       if(passWord && newPassWord){
        SQLHelp(`select passWord from user where _id = '${userId}' and passWord = '${passWord}'`).then(users =>{
           let user = users[0]
           if(user.passWord == passWord){
               SQLHelp(`update user set passWord = '${newPassWord}' where _id = '${userId}'`).then(ret =>{
                   res.send({msg:'修改密码成功'})
               })
           }else{
               res.send({errorMsg:'原密码错误'})
           }
        })
       }else{
           res.send({errorMsg:'原密码和新密码不能为空'})
       }  
   })
   //分页获取首页项目列表
   app.get('/admin/index',(req,res) => {
       let pageSize = req.query.pageSize || 10
       let pageNum = req.query.pageNum || 1
       let offset = (pageNum - 1) * pageSize
       let title = req.query.title
       let type = req.query.type
       let sql = `from index_region where state = 1`
       if(type) sql += ` and type = '${type}'`
       //模糊查询
       if(title) sql += ` and title like "%${title}%"`
       SQLHelp(`select count(*) as total ${sql};
       select * ${sql} limit ${pageSize} offset ${offset}
       `).then(ret => {
           res.send({
               total:ret[0][0].total,
               rows:ret[1]
           })
       }) 
   })
    //新增首页项目
    app.post('/admin/index',(req,res) => {
        let img = req.body.img,url = req.body.url,status = req.body.status
        let type = req.body.type || 'banner',title = req.body.title
        if(type != 'banner' && !title){
            res.send({errorMsg:'标题不能为空'})
            return
        }
        if(status != 1) status = 0
        if(img){
            let createTime = new Date().getTime()
            SQLHelp(`
            insert into index_region(title,img,url,status,state,createTime,unitId,type)
            values ('${title}','${img}','${url}','${status}',1,'${createTime}','juzao','${type}')
            `).then(ret => {
                res.send(ret.insertId ? {_id:ret.insertId} : {errorMsg:'新增数据失败'})
            })
        }else{
            res.send({errorMsg:'传入参数错误'})
        }
    })
    //修改首页项目
    app.put('/admin/index',(req,res) => {
        if(req.body.indexId){
            let updateTime = new Date().getTime()
            let updatekey = ['img','url','title','status']
            let updatevalues = [`updateTime = ${updateTime}`]
            for(let i = 0;i < updatekey.length;i++){
                let key = updatekey[i],value = req.body[key]
                if(value !== undefined) updatevalues.push(`${key}='${value}'`)
            }
            SQLHelp(`update index_region set ${updatevalues.join(',')} where _id = '${req.body.indexId}'`).then(ret => {
                res.send(ret)
            }) 
        }else{
            res.send({errorMsg:'传入参数错误'})
        }   
    })
    //删除首页项目
    app.delete('/admin/index',(req,res) => {
        let indexId = req.query.indexId
        if(indexId){
            SQLHelp(`
            update index_region
            set state = 0
            where _id = '${indexId}'
            `).then(ret => {
                res.send(ret)
            }) 
        }else{
            res.send({errorMsg:'传入参数错误'})
        }   
    })
     //分页获取新闻列表
   app.get('/admin/index/news',(req,res) => {
    let pageSize = req.query.pageSize || 10
    let pageNum = req.query.pageNum || 1
    let offset = (pageNum - 1) * pageSize
    let title = req.query.title
    let type = req.query.type
    let sql = `from article where state = 1`
    if(type) sql += ` and type = '${type}'`
    //模糊查询
    if(title) sql += ` and title like "%${title}%"`
    SQLHelp(`select count(*) as total ${sql};
    select * ${sql} limit ${pageSize} offset ${offset}
    `).then(ret => {
        res.send({
            total:ret[0][0].total,
            rows:ret[1]
        })
    }) 
})
 //新增新闻项目
 app.post('/admin/index/news',(req,res) => {
     let img = req.body.img,url = req.body.url,status = req.body.status
     let type = req.body.type || 'news',title = req.body.title,hot=req.body.hot,digest=req.body.digest
     if(type != 'news' && !title){
         res.send({errorMsg:'标题不能为空'})
         return
     }
     if(status != 1) status = 0
     if(title){
         let createTime = new Date().getTime()
         SQLHelp(`
         insert into article(title,img,status,state,createTime,unitId,type,hot,digest)
         values ('${title}','${img}','${status}',1,'${createTime}','juzao','${type}','${hot}','${digest}')
         `).then(ret => {
             res.send(ret.insertId ? {_id:ret.insertId} : {errorMsg:'新增数据失败'})
         })
     }else{
         res.send({errorMsg:'传入参数错误'})
     }
 })
 //修改新闻项目
 app.put('/admin/index/news',(req,res) => {
     if(req.body.indexId){
         let updateTime = new Date().getTime()
         let updatekey = ['img','title','digest','status','hot']
         let updatevalues = [`updateTime = ${updateTime}`]
         for(let i = 0;i < updatekey.length;i++){
             let key = updatekey[i],value = req.body[key]
             if(value !== undefined) updatevalues.push(`${key}='${value}'`)
         }
         SQLHelp(`update article set ${updatevalues.join(',')} where _id = '${req.body.indexId}'`).then(ret => {
             res.send(ret)
         }) 
     }else{
         res.send({errorMsg:'传入参数错误'})
     }   
 })
 //删除新闻项目
 app.delete('/admin/index/news',(req,res) => {
     let indexId = req.query.indexId
     if(indexId){
         SQLHelp(`
         update article
         set state = 0
         where _id = '${indexId}'
         `).then(ret => {
             res.send(ret)
         }) 
     }else{
         res.send({errorMsg:'传入参数错误'})
     }   
 })
    //分页获取单品列表
    app.get('/admin/index/sku',(req,res) => {
        let pageSize = req.query.pageSize || 10
        let pageNum = req.query.pageNum || 1
        let offset = (pageNum - 1) * pageSize
        let productName = req.query.productName
        let sql = `from sku where state = 1`
        //模糊查询
        if(productName) sql += ` and productName like "%${productName}%"`
        SQLHelp(`select count(*) as total ${sql};
        select * ${sql} limit ${pageSize} offset ${offset}
        `).then(ret => {
            res.send({
                total:ret[0][0].total,
                rows:ret[1]
            })
        }) 
    })
     //新增单品项目
     app.post('/admin/index/sku',(req,res) => {
         let skuId = req.body.skuId,img = req.body.img,salePrice = req.body.salePrice,originalPrice = req.body.originalPrice
         let productName = req.body.productName,props = req.body.props,productId=req.body.type
         if(!skuId){
             res.send({errorMsg:'SKU编码不能为空'})
             return 
         }
         if(skuId){
             let createTime = new Date().getTime()
             SQLHelp(`
             insert into sku(skuId,img,salePrice,state,createTime,unitId,originalPrice,productName,props,productId)
             values ('${skuId}','${img}','${salePrice}',1,'${createTime}','juzao','${originalPrice}','${productName}','${props}','${productId}')
             `).then(ret => {
                 res.send(ret.insertId ? {_id:ret.insertId} : {errorMsg:'新增数据失败'})
             })
         }else{
             res.send({errorMsg:'传入参数错误'})
         }
     })
     //修改单品项目
     app.put('/admin/index/sku',(req,res) => {
         if(req.body.indexId){
             let updateTime = new Date().getTime()
             let productId = req.body.type
             let updatekey = ['img','skuId','salePrice','originalPrice','productName','props']
             let updatevalues = [`updateTime = ${updateTime},productId = ${productId}`]
             for(let i = 0;i < updatekey.length;i++){
                 let key = updatekey[i],value = req.body[key]
                 if(value !== undefined) updatevalues.push(`${key}='${value}'`)
             }
             SQLHelp(`update sku set ${updatevalues.join(',')} where _id = '${req.body.indexId}'`).then(ret => {
                 res.send(ret)
             }) 
         }else{
             res.send({errorMsg:'传入参数错误'})
         }   
     })
     //删除单品项目
     app.delete('/admin/index/sku',(req,res) => {
         let indexId = req.query.indexId
         if(indexId){
             SQLHelp(`
             update sku
             set state = 0
             where _id = '${indexId}'
             `).then(ret => {
                 res.send(ret)
             }) 
         }else{
             res.send({errorMsg:'传入参数错误'})
         }   
     })
    //分页获取品牌列表
    app.get('/admin/index/pinpai',(req,res) => {
        let pageSize = req.query.pageSize || 10
        let pageNum = req.query.pageNum || 1
        let offset = (pageNum - 1) * pageSize
        let name = req.query.name
        let sql = `from brand where state = 1`
        //模糊查询
        if(name) sql += ` and name like "%${name}%"`
        SQLHelp(`select count(*) as total ${sql};
        select * ${sql} limit ${pageSize} offset ${offset}
        `).then(ret => {
            res.send({
                total:ret[0][0].total,
                rows:ret[1]
            })
        }) 
    })
    //新增品牌项目
    app.post('/admin/index/pinpai',(req,res) => {
        let img = req.body.img,sort = req.body.sort,banner = req.body.banner
        let name = req.body.name
        if(!name){
            res.send({errorMsg:'标题不能为空'})
            return 
        }
        if(name){
            let createTime = new Date().getTime()
            SQLHelp(`
            insert into brand(name,img,sort,state,createTime,unitId,banner)
            values ('${name}','${img}','${sort}',1,'${createTime}','juzao','${banner}')
            `).then(ret => {
                res.send(ret.insertId ? {_id:ret.insertId} : {errorMsg:'新增数据失败'})
            })
        }else{
            res.send({errorMsg:'传入参数错误'})
        }
    })
    //修改品牌项目
    app.put('/admin/index/pinpai',(req,res) => {
        if(req.body.indexId){
            let updateTime = new Date().getTime()
            let updatekey = ['img','name','sort','banner']
            let updatevalues = [`updateTime = ${updateTime}`]
            for(let i = 0;i < updatekey.length;i++){
                let key = updatekey[i],value = req.body[key]
                if(value !== undefined) updatevalues.push(`${key}='${value}'`)
            }
            SQLHelp(`update brand set ${updatevalues.join(',')} where _id = '${req.body.indexId}'`).then(ret => {
                res.send(ret)
            }) 
        }else{
            res.send({errorMsg:'传入参数错误'})
        }   
    })
    //删除品牌项目
    app.delete('/admin/index/pinpai',(req,res) => {
        let indexId = req.query.indexId
        if(indexId){
            SQLHelp(`
            update brand
            set state = 0
            where _id = '${indexId}'
            `).then(ret => {
                res.send(ret)
            }) 
        }else{
            res.send({errorMsg:'传入参数错误'})
        }   
    })
     //分页获取商品列表
     app.get('/admin/index/good',(req,res) => {
        let pageSize = req.query.pageSize || 10
        let pageNum = req.query.pageNum || 1
        let offset = (pageNum - 1) * pageSize
        let productName = req.query.productName
        let sql1 = `from product,brand WHERE product.brandId=brand._id and product.state = 1`
        let sql2 = `product.name,brand.name as brand_name,brandId as type,description, specification,product._id,product.img,product.sales,product.status`
        //按商品名称模糊查询
        if(productName) sql1 += ` and product.name like "%${productName}%"`
        SQLHelp(`select count(*) as total ${sql1};
        select ${sql2} ${sql1} limit ${pageSize} offset ${offset}
        `).then(ret => {
            res.send({
                total:ret[0][0].total,
                rows:ret[1]
            })
        }) 
    })
    //新增商品项目
    app.post('/admin/index/good',(req,res) => {
        let img = req.body.img,sales = req.body.sales,description = req.body.description,specification = req.body.specification
        let name = req.body.name,status = req.body.status,type = req.body.type
        if(!name){
            res.send({errorMsg:'商品名称不能为空'})
            return 
        }
        if(name){
            let createTime = new Date().getTime()
            SQLHelp(`
            insert into product(name,img,brandId,state,createTime,unitId,description,specification,sales,status)
            values ('${name}','${img}','${type}',1,'${createTime}','juzao','${description}','${specification}','${sales}','${status}')
            `).then(ret => {
                res.send(ret.insertId ? {_id:ret.insertId} : {errorMsg:'新增数据失败'})
            })
        }else{
            res.send({errorMsg:'传入参数错误'})
        }
    })
    //修改商品项目
    app.put('/admin/index/good',(req,res) => {
        if(req.body.indexId){
            let updateTime = new Date().getTime()
            let brandId = req.body.type
            let updatekey = ['img','name','description','specification','sales','status']
            let updatevalues = [`updateTime = ${updateTime},brandId = ${brandId}`]
            for(let i = 0;i < updatekey.length;i++){
                let key = updatekey[i],value = req.body[key]
                if(value !== undefined) updatevalues.push(`${key}='${value}'`)
            }
            SQLHelp(`update product set ${updatevalues.join(',')} where _id = '${req.body.indexId}'`).then(ret => {
                res.send(ret)
            }) 
        }else{
            res.send({errorMsg:'传入参数错误'})
        }   
    })
    //删除商品项目
    app.delete('/admin/index/good',(req,res) => {
        let indexId = req.query.indexId
        if(indexId){
            SQLHelp(`
            update product
            set state = 0
            where _id = '${indexId}'
            `).then(ret => {
                res.send(ret)
            }) 
        }else{
            res.send({errorMsg:'传入参数错误'})
        }   
    })
     //分类列表查询数据
     app.get('/admin/index/fenlei', (req, res) => {
        SQLHelp(`
        select * from category
        `).then(ret => {
            res.send(ret)
        })
    })
    //新增分类项目
    app.post('/admin/index/fenlei',(req,res) => {
        let img = req.body.img,level = req.body.type,sort = req.body.sort
        let name = req.body.name,parentId = req.body.id
        if(level == 2){
            id = parentId + '_' + snowflake()
        }else{
            id = snowflake()
            parentId = 0
            
        }
        if(!name){
            res.send({errorMsg:'分类名称不能为空'})
            return 
        }
        if(name){
            let createTime = new Date().getTime()
            SQLHelp(`
            insert into category(id,name,img,level,state,parentId,createTime,unitId,sort)
            values ('${id}','${name}','${img}','${level}',1,'${parentId}','${createTime}','juzao','${sort}')
            `).then(ret => {
                res.send(ret.insertId ? {_id:ret.insertId} : {errorMsg:'新增数据失败'})
            })
        }else{
            res.send({errorMsg:'传入参数错误'})
        }
    })
    //修改分类项目
    app.put('/admin/index/fenlei',(req,res) => {
        if(req.body.indexId){
            let updateTime = new Date().getTime()
            let level = req.body.type
            let updatekey = ['img','name','sort','level']
            let updatevalues = [`updateTime = ${updateTime},level = ${level}`]
            for(let i = 0;i < updatekey.length;i++){
                let key = updatekey[i],value = req.body[key]
                if(value !== undefined) updatevalues.push(`${key}='${value}'`)
            }
            SQLHelp(`update category set ${updatevalues.join(',')} where _id = '${req.body.indexId}'`).then(ret => {
                res.send(ret)
            }) 
        }else{
            res.send({errorMsg:'传入参数错误'})
        }   
    })
     //删除分类项目
     app.delete('/admin/index/fenlei',(req,res) => {
        let indexId = req.query.indexId
        if(indexId){
            SQLHelp(`
            update category
            set state = 0
            where _id = '${indexId}'
            `).then(ret => {
                res.send(ret)
            }) 
        }else{
            res.send({errorMsg:'传入参数错误'})
        }   
    })
     //分页获取分类详情商品列表
     app.get('/admin/index/fp',(req,res) => {
        let pageSize = req.query.pageSize || 10
        let pageNum = req.query.pageNum || 0
        let offset = (pageNum - 1) * pageSize
        let name = req.query.name
        let title = req.query.title
        let sql = `FROM category_product,product WHERE product._id = category_product.productId and category_product.categoryId = (SELECT id FROM category WHERE name='${title}')`
        
        //按商品名称模糊查询
        if(name) sql += ` and product.name like "%${name}%"`
        SQLHelp(`select count(*) as total ${sql};
        select * ${sql} limit ${pageSize} offset ${offset};
        `).then(ret => {
            res.send({
                total:ret[0][0].total,
                rows:ret[1]
            })
        }) 
    })
   //新增商品项目
   app.post('/admin/index/good',(req,res) => {
    let img = req.body.img,sales = req.body.sales,description = req.body.description,specification = req.body.specification
    let name = req.body.name,status = req.body.status,type = req.body.type
    if(!name){
        res.send({errorMsg:'商品名称不能为空'})
        return 
    }
    if(name){
        let createTime = new Date().getTime()
        SQLHelp(`
        insert into product(name,img,brandId,state,createTime,unitId,description,specification,sales,status)
        values ('${name}','${img}','${type}',1,'${createTime}','juzao','${description}','${specification}','${sales}','${status}')
        `).then(ret => {
            res.send(ret.insertId ? {_id:ret.insertId} : {errorMsg:'新增数据失败'})
        })
    }else{
        res.send({errorMsg:'传入参数错误'})
    }
})
//修改商品项目
app.put('/admin/index/good',(req,res) => {
    if(req.body.indexId){
        let updateTime = new Date().getTime()
        let brandId = req.body.type
        let updatekey = ['img','name','description','specification','sales','status']
        let updatevalues = [`updateTime = ${updateTime},brandId = ${brandId}`]
        for(let i = 0;i < updatekey.length;i++){
            let key = updatekey[i],value = req.body[key]
            if(value !== undefined) updatevalues.push(`${key}='${value}'`)
        }
        SQLHelp(`update product set ${updatevalues.join(',')} where _id = '${req.body.indexId}'`).then(ret => {
            res.send(ret)
        }) 
    }else{
        res.send({errorMsg:'传入参数错误'})
    }   
})
//删除商品项目
app.delete('/admin/index/good',(req,res) => {
    let indexId = req.query.indexId
    if(indexId){
        SQLHelp(`
        update product
        set state = 0
        where _id = '${indexId}'
        `).then(ret => {
            res.send(ret)
        }) 
    }else{
        res.send({errorMsg:'传入参数错误'})
    }   
})
}